package com.car.carsharing.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@RestController
public class AlipayConfig {
    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    public static String app_id ="2021000117660046";

    // 商户私钥，您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCj1+Q30hH6mvYz3mca80vrGvHSpBrPZiDzxe3Tj5VhUgLLckl2dgdTsbEIxFmMvqg35FcMB0tYUcozQiw/TGRSqn74vM4K/WEvAmCEIlRAJ/mhaTxycF9iDQivFyVwuZomR+htq8jpBRS7QXESwAYTAsLAIpbw94h5iUPChq39fZlASg4ckKQWo/qktldVxdVdgdxrt1YMC35+N33aQQBNsm+Oe9W981H4WGYgEaVSRBBFtN5Z0Wxd911rR2T9iOw1DVnUV+B7l2fkZjaDmuV3J41sCeiwH6jJLa/fdwtNmCuGq7UCsx59FrUeJ+5b63kP9BieHs9jm9YzbOaHtKS1AgMBAAECggEAEhFNpmYw+1y5R7D/17X6qjt3bU4RcsuFWLx75HeR9oBvtHWu6jRLzIvsxNW6Nk4UCM3SV446XcvvK0Xh0T0gVwlcJRvU8NtOKzvs3sVWWxjNa2JKeygvLIXZbk10IIEnIY+ObwGhjyizR48I5BNu2AvW5A8sa/gwAY8EfOATMb/JxLnjdz/MWoSDab5UP4dDk9dURVoat0mresc9du/5ItH5UXgcZJRuCuK4cNUEaxlvcWDvajr2O+zTeNQwlKTHRud7CwMDKCr5mgfVH0ueePIfMvhe+xRbJvEVrl+Em5d5wNrI5pMXTsDGbMggJ/9OU1/IcQr1mj4x3V3ZG/jb4QKBgQDTOoAFu9C/y2wBp7KLot+pq+FF3PpEJ7LYttvVZsbMH65mnoyogi0H6AWybQmib2uXBSqnhz0ChmoD6d+2AYk5Uv4E71+okj0vIAJBzq7Lmh5wSKFFKNOfgLBnU3dIsi1/oqVDHwA8mr6HjOJj7exIEJZfNjlS6RTObgRCX6oPfQKBgQDGkjeNj/5/byRZ0zCSABErjGa9JOrnjEWQHp03hGTXYSmK7EVCQAgVKp13vpkqKnCqdfq5WXTDtqRuYbaydjHKD40em/8w0hM1FT7BsYfl/At7ZRkCn19ebcf3xFBrG+1njHDvKri7NUQfV94JqepsGA1JKExm3RSlhidpQTpfmQKBgEcagS/s6jc11dS0y8B/gkTOTBXFbiV1K5oR6+xpHXBnFcELjBPJRjlMHGbUl5KraQ88OQCN4Lax4owQtTLCT5wRWNr2bUAEgj4Ty061sVduOOLZQBhUxvABVOBjU1sQR4qYiIMQs3azLIHapfa3h3s2wjeovCExvsRCeoKRS2DNAoGASfpvd+4NgqyFfnGPxtT/kJneLNl0Ko+32tmM+QH6D8PDFl6v7t6sJDacM+Bub6cgEmGh5yvMtJ125SjCR/qA0ia5DI5RpH6faUdg+giJ+MTOAkrH5pI5lZSQy134F+9vowRPjsr7x8MwffzeW/tRurO7P2YkEK6M4p34UN5cQQECgYB/g8kc6vQCLTB2dL56FAyHzLdw6dbFDpGXmSr/QvlCBLyLPsvOX+2xsLPjIU5AUNRFXP76xOpspC75hMahhso+sbdfaz1lYPhnWEBtu4gWhxKyb70iU6JnFM5MMMWmP5dSv3i1mKaNqWSRx6kV1IAAP+4WL+CuMrzBWGvVqm3xZg==";
    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoTVpGN5KAZak9et/rGcCH81LParOVLQqQ17jrjUTvKSDdZfzJmBn6Hft4xLIBYQP26PKqXFTaUXXZ8U1RXkhsGHFoQCAnUHUWlK+EROkkCa0XRk6ZJ3rzAK+/8zy44WSf5hHOdvj30CxnvgEZ+t2I/F76Fw0h5mybHdnT4z5FqZ3z1+xOoZwdoCN3aQoLHRw74Zlwx5sNdQusLPpV0M3V23rOyzO7kwKM9911aQ7VTnydcSVgY+Gn+bYvyuKFfNAhsEZ/TZp7/eAdLsFBvBEazpCPWm6kcPB4tr/i8fn9Be+/5IcsSF2UgGUR1t3mDzL6s00lipM8Cm20spYoCaP2QIDAQAB";
    // 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    public static String notify_url = "http://localhost:8082/alipay/notify_url";
    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    public static String return_url = "http://localhost:8082/alipay/return_url";
    // 签名方式
    public static String sign_type = "RSA2";

    public  String urlStr="";

    // 字符编码格式
    public static String charset = "utf-8";

    // 支付宝网关
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    @RequestMapping("/toPay")
    public void toPay(HttpServletRequest request, HttpServletResponse response,String viewUrl,String money,String name,String detail) throws Exception{
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,app_id,merchant_private_key, "json",charset,alipay_public_key,sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = UUID.randomUUID().toString();
        System.out.println("out_trade_no="+out_trade_no);
        //付款金额，必填
        String total_amount = money;
        //订单名称，必填
        String subject = name;
        //商品描述，可空
        String body = detail;

        urlStr = viewUrl;

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = "";
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        response.setContentType("text/html;charset=" + charset);
        response.getWriter().write(result);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    //回调验证.验证成功后可以返回自己想要跳转的页面
    @RequestMapping("/alipay/return_url")
    public void returnUrl(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException{
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);
        boolean signVerified = AlipaySignature.rsaCheckV1(params,alipay_public_key,charset,sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
//            return "trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount;
            response.setContentType("text/html; charset=GB2312");
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.print("<script>window.onload=function(){window.location.href='"+urlStr+"';}</script>");
            out.close();
        }else {
            response.setContentType("text/html; charset=GB2312");
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.print("<script>alert('失败！！');</script>");
            out.close();
        }
    }

}
